<template>
  <el-container style="display: flex; justify-content: center; height: 100%">
    <el-card class="box-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="20" type="flex" justify="space-between" align="middle">
          <el-row :span="8">
            <el-form-item label="">
              <el-button type="success" @click="back" style="margin-left: 25px;">返回上一级</el-button>
            </el-form-item>
          </el-row>
        </el-row>
      </el-form>
      <el-table :data="mergedData" border>
        <el-table-column prop="id" label="序号" width="80"/>
        <el-table-column prop="userName" label="姓名" width="150" >
          <template #default="{ row }">
            <div v-for="item,index in row.staffid" :key="index">
              <span>{{ findName(item) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="'组别'" width="100">
          <template #default="{ row }">
          {{ getGroupName(row.matchesGroupId) }}
        </template>
        </el-table-column>
        <el-table-column :label="'单位'" width="120">
          <template #default="{ row }">
          {{ getTeamName(row.teamGroupId) }}
        </template>
        </el-table-column>
        <el-table-column :label="'项目'" width="120">
          <template #default="{ row }">
          {{ getProjectName(row.projectId) }}
        </template>
        </el-table-column>
        <el-table-column :label="'申报难度'">
          <template #default="{ row }">
          <div v-if="row.userCodes.length === 0">暂无数据</div>
          <div v-for="item,index in row.userCodes" :key="index">
             <span>{{ `(${item.code})${item.content}(${item.score})` }}</span>
          </div>
        </template>
        </el-table-column>
      </el-table>
    </el-card>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();

const id = route.query.projectid;
const matchid = route.query.matchid;

const token = localStorage.getItem('adminToken');
const searchForm = ref({});
const tableData = ref([]);
const Team = ref([]);
const group = ref([]);
const staff = ref([]);
const project = ref([]);

const mergedData = ref([]);

// 获取渲染页面的数据
async function handleProjectChange() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/api/getProjectDifficultyDeclare/${id}`, {
      headers: { 'Authorization': 'Bearer ' + token }
    });
    if (response.data.suceess) {
      tableData.value = response.data.data;
    }
    const data = response.data.data;
    // 假设 data 是一个数组，每个元素都是一个对象，包含 routineid 和 staffid 属性
    mergedData.value = data.reduce((acc, current) => {
    const existingItem = acc.find(item => item.routineid === current.routineid);

      if (existingItem) {
        // 确保 staffid 为数组
        const currentStaffIds = Array.isArray(current.staffid) ? current.staffid : [current.staffid];
        const existingStaffIds = Array.isArray(existingItem.staffid) ? existingItem.staffid : [existingItem.staffid];

        // 合并 staffid 数组
        existingItem.staffid = [...new Set([...existingStaffIds, ...currentStaffIds])];
      } else {
        // 如果没有找到，添加新项到累加器数组
        acc.push({
          ...current,
          staffid: Array.isArray(current.staffid) ? current.staffid : [current.staffid]
        });
      }

      return acc;
    }, []);    
  } catch (error) {
    console.error('没有获取到数据:', error);
    tableData.value = [];
  }
}

// 获取所有人员的信息
async function fetchstaff() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/team/staff/${matchid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });    
    staff.value = response.data.data; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

// 获取所有比赛的团队信息
async function fetchTeamData() {
  try {
    const response = await axios.get('http://back1.idcfengye.com:15173/api/getAllTeam', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    Team.value = response.data.data; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

// 获取所有比赛的组别信息
async function fetchgroupData() {
  try {
    const response = await axios.get('http://back1.idcfengye.com:15173/competition/group/admin', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    group.value = response.data.data; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

// 获取所有比赛的组别信息
async function fetchprojectData() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    project.value = response.data.project; // 确保后端返回的数据结构与此匹配
  } catch (error) {
    console.log(error);
  }
}

// 根据队伍id获取比赛名称
function getTeamName(id) {
  const data = Team.value.find(user => user.id === id);
  return data ? data.teamName : '团队名称未找到';
}

// 根据队伍id获取比赛名称
function getProjectName(id){
  const data =  project.value.find(user => user.id === id);
  return `${data.projectName}`;
}

//根据组别的id渲染页面的组别name
function getGroupName(id){
  const data =  group.value.find(user => user.id === id);
  return `${data.groupname}`;
}

//获取本项目需要的人员
function findName(item){
  const data =  staff.value.find(user => user.id === item);
  return `(${data.id}${data.sex})${data.userName}`;
}

onMounted(() => {
  fetchstaff();
  fetchTeamData();
  fetchgroupData();
  fetchprojectData();
  handleProjectChange();
});

//返回上一级页面
function back() {
  router.push({ path: '/admin/viewproject', query: { id: matchid } });
}
</script>

<style scoped></style>